package cn.shujuhai.cms.aop;

import cn.shujuhai.cms.domain.InfoArticle;
import cn.shujuhai.cms.domain.SysChannel;
import cn.shujuhai.cms.service.InfoArticleService;
import cn.shujuhai.cms.service.SysChannelService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @Author: ZhangDeZhong
 * @Date: 2024/12/12 09:24
 * @Description: 栏目和文章浏览量切面处理类
 **/
@Aspect
@Component
@RequiredArgsConstructor
public class CountAspect {
    private final SysChannelService sysChannelService;

    private final InfoArticleService infoArticleService;

    @Pointcut("@annotation(Count)")
    public void logPointcut() {
    }

    /**
     * 计算栏目或文章浏览量
     *
     * @param joinPoint 连接点
     */
    @AfterReturning(pointcut = "logPointcut()")
    public void count(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Count count = method.getAnnotation(Count.class);
        Object[] args = joinPoint.getArgs();
        // 获取当前请求的 IP 地址和时间
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        LocalDateTime time = LocalDateTime.now();

        if (count.module().equals("channel")) {
            this.sysChannelService.update(Wrappers.<SysChannel>lambdaUpdate()
                    .setSql("count = count + 1")
                    .eq(SysChannel::getUrlKey, args[0]));
        } else if (count.module().equals("info")) {
            this.infoArticleService.update(Wrappers.<InfoArticle>lambdaUpdate()
                    .setSql("count = count + 1")
                    .eq(InfoArticle::getArticleId, args[1]));
        }
        System.out.println("Module: " + count.module() + ", IP: " + ip + ", Time: " + time + ", Args: " + java.util.Arrays.toString(args));
    }
}
